<html>
<head><title>CS143 Project 1B Demo</title></head>
<body>
	<h3>Web Quesry</h3>
	<form action="query.php" method="GET">
		<textarea name="query" cols="60" rows="8"></textarea>
		<input type="submit" value="Submit" />
	</form>
	<?php
		error_reporting(0);
		if($_GET['query'])
		{
			echo "<h3>Results from MySQL</h3>";
			$rs = getResult($_GET['query']);
			if(!empty($rs))
			{
				echo "<table border=1 cellspacing=1 cellpadding=2>";
				/*Print Column Attributes*/
				echo "<tr align=center>";
				foreach(array_keys($rs[0]) as $key)
					echo "<td><b>".$key."</b></td>";
				echo "</tr>";
				/*Print row Content*/
				foreach($rs as $row)
				{
					echo "<tr align=center>";
					foreach($row as $col)
					{
						echo "<td>".$col."</td>";
					
					}
					echo "</tr>";
				}
				echo "</table";
			}else{
			
			}
			
		}
	
	?>
	</p>
	<p><small>Note: tables and fields are case sensitive. Run "show tables" to see the list of
	available tables.</small>
	</p>


</body>
</html>
<?php
	function getResult($q){
		$mysqli = new mysqli("localhost", "cs143", "", "CS143");
		/* Check Connection */
		if ($mysqli->connect_errno) {
		    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
		}	
		/* Check Query */
		if(!($data = $mysqli->query($q)))
		{
			 echo $mysqli->error;
		}
			
		$result = array();
		while($data_obj = $data->fetch_assoc()){
			$result[] =$data_obj;
		}
		
		/* Close Connection */
		$mysqli->close();
		
		/* Return result array */
		return $result;
	}


?>